package com.shike.core.interceptors;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.shike.core.dto.JwtUserDto;
import com.shike.core.utils.JWTUtil;
import com.shike.core.utils.R;
import com.shike.core.utils.ResponseUtil;
import com.shike.core.utils.SysCode;
import com.shike.core.utils.redis.RedisUtil;
import com.shike.core.utils.redis.impl.RedisTokenKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author doumuxie https://gitee.com/lyears/
 * @version 1.0
 * @date 2020/2/27 11:12
 * @description CheckToken 注解拦截器 （用于校验用户是否已经登录 并 进行授权）
 **/
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = request.getHeader(SysCode.TOKEN);
        if (StringUtils.isEmpty(token)) {
            ResponseUtil.sendResponse(response, R.error("用户未登录"));
            return false;
        }
        // 解析token
        JwtUserDto dto = JWTUtil.getJwtUser(token);
        if (dto == null) {
            // token 无效
            ResponseUtil.sendResponse(response, R.error("无效Token"));
            return false;
        }
        if (redisUtil.exists(RedisTokenKey.TOKEN_KEY, dto.getUserId())) {
            redisUtil.setExpire(RedisTokenKey.TOKEN_KEY, dto.getUserId());
            return true;

        }else{
            // token 无效
            ResponseUtil.sendResponse(response, R.error("用户身份已过期"));
            return false;
        }
    }


}
